<?php defined('SYSPATH') or die('No direct script access.');

	class Model_Services_Medic extends Model implements Jqgrid_GridListener{
	
		public $medic;
		
		public function __construct($id=false){
			if ($id) $this->medic = $this->get($id);
		}
		
		public function count($criteria = false){
			return ORM::factory("dao_medic")->count_all();
		}
			
		public function getList($criteria = false){
			
			if (!$criteria)	$medic_list = ORM::factory("dao_medic")->find_all()->as_array();
			else{
				if ($criteria->isSearch){
					$medic_list = ORM::factory("dao_medic")
									->where($criteria->getSQLField("medics"),$criteria->getSQLOper(), $criteria->getSQLSearchString())
									->order_by($criteria->sidx,$criteria->sord)
									->limit($criteria->limit)
									->offset($criteria->calcOffset())
									->find_all()
									->as_array();
							
				}else{
					$medic_list = ORM::factory("dao_medic")->order_by($criteria->sidx,$criteria->sord)->limit($criteria->limit)->offset($criteria->calcOffset())->find_all()->as_array(); 
				}
				
				
			} 
		
			$dataset = array();
			foreach ($medic_list as $medic){
				$dataset[$medic->id] = array($medic->surname, $medic->name, $medic->doctype->description, $medic->identity_card_number, Helper_Date::mysqlToDate($medic->birthdate), $medic->sex, $medic->address, $medic->phone, $medic->cel, $medic->email, $medic->city, $medic->specialty);
			}
			
			return $dataset;
		}
	
		
		/**
		*
		* get all medics from an id
		* @param int $minId
		* @param int $maxAmount
		* @return array of medics
		*/
		public function getListFromMinID($minId, $maxAmount){
			return ORM::factory("dao_medic")->where("id",">",$minId)->order_by("id", "ASC")->limit($maxAmount)->find_all()->as_array();
		}
		
		public function get($id){
			return ORM::factory("dao_medic")->find($id);
		}
		
		public function getFullname(){
			return $this->medic->surname.", ".$this->medic->name;
		}
		
		public function save($id, array $data){
			$this->medic = ($id > 0) ? ORM::factory("dao_medic",$id) : ORM::factory("dao_medic");
			
			$this->medic->doctype_id = $data['doctype'];
			$this->medic->identity_card_number = $data['identity_card_number'];
			$this->medic->surname = $data['surname'];
			$this->medic->name = $data['name'];
			$this->medic->birthdate = Helper_Date::dateToMysql($data['birthdate']);
			$this->medic->address = $data['address'];
			$this->medic->phone = $data['phone'];
			$this->medic->cel = $data['cel'];
			$this->medic->email = $data['email'];
			$this->medic->sex = $data['sex'];
			$this->medic->city = $data['city'];
			$this->medic->specialty = $data['specialty'];
				
			
			$this->medic->save();
			return $this->medic->id;
	    }
		
		public function delete($id){
			$medic = ORM::factory("dao_medic",$id);
			$medic->delete();
			return "Medico".$id." eliminado con exito";
		}
		
		
	}
	
?>	
